package com.wh.db;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 
 * @author washheart@163.com
 * 
 * @param <T>
 */
public class Page<T> implements Serializable {
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static final Page EMPTY_PAGE = new Page(Collections.EMPTY_LIST, 0, 0, 0, false);

	public static final int PageCount = 20;

	private int start;// 开始条数
	private int count;// 每页页数
	private int total;// 总共记录数量

	private List<T> list;// 本页要输出的内容
	private boolean hasNext;// (计算得来)是否还有下一页
	private int currentPage;// (计算得来)当前页码
	private int totalPage;// (计算得来)总页码

	@Override
	public String toString() {
		return "Page[start=" + start + ",count=" + count + ",total=" + total + ",hasNext" + hasNext + "]size=" + list.size();
	}

	public Page(List<T> list, int start, int count, int total, boolean hasNext) {
		init(list, start, count, total, hasNext);
	}

	public Page(final List<T> list, int start, int count) {
		int total = list.size();
		boolean hasNext = (start - 1 + count) < total;
		start--;
		int size = total - start;
		size = (size < count) ? size : count;
		size = (size < 0) ? 0 : size;
		List<T> pageList = new java.util.ArrayList<T>(size); // 建立一个链表存放页面数据
		for (int i = 0; i < size; i++) {
			pageList.add(list.get(start + i));
		}
		start++;
		init(pageList, start, count, total, hasNext);
	}

	private void init(List<T> pageList, int start, int count, int total, boolean hasNext) {
		this.list = new ArrayList<T>(pageList);
		this.start = start;
		this.hasNext = hasNext;
		this.count = count;
		this.total = total;
		this.totalPage = 1;
		this.currentPage = 1;
		if (total != 0) {
			if (total % count == 0) totalPage = total / count;
			else totalPage = total / count + 1;
			if (start != 0) currentPage = (start - 1) / count + 1;
		}
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public int getTotalPage() {
		return this.totalPage;
	}

	public int getStartOfNextPage() {
		return start + list.size();
	}

	public int getStartOfPreviousPage() {
		return Math.max(start - count, 1);
	}

	public int getFirstPage() {
		return 1;
	}

	public int getLastPage() {
		return this.totalPage;
	}

	public List<T> getList() {
		return list;
	}

	public int getStart() {
		if (start > 1) return start;
		else return 1;
	}

	public boolean hasNextPage() {
		return hasNext;
	}

	public boolean hasPreviousPage() {
		return start > 1;
	}

	public int getSize() {
		return list.size();
	}

	public int getCount() {
		return count;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public boolean isHasPreviousPage() {
		return hasPreviousPage();
	}

	public boolean isHasNextPage() {
		return hasNextPage();
	}
}
